
import {defineDateField} from "./dateField.js";
import {$} from "../util/seq.js";
import {debounce} from "underscore";

export function defineLayerDetails(container, sessionStore, primaryLayerAgent, activeLayerAgent) {

    defineDateField(container.selectAll("[data-name=date]"), sessionStore, activeLayerAgent);

    const description = container.selectAll("[data-name=description]");
    const source = container.selectAll("[data-name=source]");

    function updateDOM() {
        const primaryLayer = primaryLayerAgent.value();
        const activeLayer = activeLayerAgent.value();
        const primaryName = primaryLayer?.descriptionHTML.name ?? "";
        const primaryQual = primaryLayer?.descriptionHTML.qualifier ?? "";
        const activeName = activeLayer?.descriptionHTML.name ?? "";
        const activeQual = activeLayer?.descriptionHTML.qualifier ?? "";

        let descriptionHTML = activeName + activeQual;
        if (descriptionHTML && primaryLayer !== activeLayer) {
            // Combine both layer descriptions together with a " + " if their qualifiers are the same.
            if (primaryQual === activeQual) {
                descriptionHTML = `${primaryName} + ${descriptionHTML}`;
            } else {
                descriptionHTML = `${primaryName + primaryQual} + ${descriptionHTML}`;
            }
        }

        description.html(descriptionHTML);
        source.html(activeLayer?.sourceHTML ?? "");
    }

    const updateDOM_debounced = debounce(updateDOM);

    primaryLayerAgent.on($`update`, updateDOM_debounced);
    activeLayerAgent.on($`update`, updateDOM_debounced);
}
